<template>
	<view>
		<view class="big_box" style="width: 100vh;height: 100vh;position: relative;">
			<image
				src="https://baijixing.oss-cn-chengdu.aliyuncs.com/2025/APRIL/16/1744795906255_979eba4d-b542-4ce4-a20d-fe019310d479.jpg"
				mode="aspectFill" class="beijin"></image>
			<image
				src="https://baijixing.oss-cn-chengdu.aliyuncs.com/2025/APRIL/25/1745566460978_52fd14fa-df94-44f4-bfcc-b39b7a7ac6c8.png"
				mode="aspectFill" class="bottm"></image>
			<view class="download-btn" @click="startDownload">
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: true,
				url: '',
				downloading: false,
				progress: 0,
				tempFilePath: ''
			}
		},
		onShow() {
			//#ifdef H5
			if (this.$jwx && this.$jwx.isWechat()) { 
				this.show = true
			} else {
				this.show = false
			}
			//#endif
			this.cread()
		},
		methods: {
			async cread() {
				try {
					let res = await this.$request("worker/app/version")
					let url = res.data.path
					this.url = url
				} catch (error) {
					console.error('获取下载链接失败:', error)
					wx.showToast({
						title: '获取下载链接失败',
						icon: 'none'
					})
				}
			},
			// 清理缓存
			async clearStorage() {
				return new Promise((resolve, reject) => {
					wx.getStorageInfo({
						success: (res) => {
							console.log('当前缓存信息:', res)
							wx.clearStorage({
								success: () => {
									console.log('缓存清理成功')
									resolve()
								},
								fail: (err) => {
									console.error('缓存清理失败:', err)
									reject(err)
								}
							})
						},
						fail: (err) => {
							console.error('获取缓存信息失败:', err)
							reject(err)
						}
					})
				})
			},
			//#ifdef H5
			startDownload(){
				uni.navigateTo({
					url:'/pages/down/down'
				})
			},
			//#endif
			//#ifdef MP-WEIXIN
			startDownload() {
				if (!this.url) {
					wx.showToast({
						title: '下载链接获取中，请稍候',
						icon: 'none'
					})
					return
				}
				
				if (this.downloading) {
					return
				}
				
				this.downloading = true
				this.progress = 0
				
				wx.showLoading({
				  title: '正在下载',
				  content: '0%',
				  showCancel: false,
				  confirmText: '下载中...',
				  mask:true,
				  confirmColor: '#999999'
				})
				
				
				wx.downloadFile({
					url: this.url,
					success: async (res) => {
						wx.hideLoading()
						this.downloading = false
						if (res.statusCode === 200) {
							this.tempFilePath = res.tempFilePath
							
							// 尝试保存文件
							wx.saveFile({
								tempFilePath: res.tempFilePath,
								success: (saveRes) => {
									// 保存成功，使用永久路径
									this.handleDownloadSuccess(saveRes.savedFilePath)
								},
								fail: (saveErr) => {
									console.error('保存文件失败:', saveErr)
									
									// 检查是否是存储限制错误
									if (saveErr.errMsg.includes('exceeded the maximum size')) {
										wx.showModal({
											title: '存储限制',
											content: '由于微信限制，无法保存超过10MB的文件。是否直接打开临时文件？',
											confirmText: '打开',
											cancelText: '取消',
											success: (modalRes) => {
												if (modalRes.confirm) {
													// 使用临时路径打开文件
													this.handleDownloadSuccess(res.tempFilePath, true)
												}
											}
										})
									} else {
										wx.showToast({
											title: '保存文件失败',
											icon: 'none'
										})
									}
								}
							})
						} else {
							console.error('下载失败，状态码:', res.statusCode)
							wx.showToast({
								title: '下载失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('下载API调用失败:', err)
						wx.hideLoading()
						this.downloading = false
						
						// 提示用户在浏览器中下载
						if (err.errMsg.includes('request:fail')) {
							wx.showModal({
								title: '下载失败',
								content: '由于文件过大或网络限制，建议在浏览器中下载。是否复制下载链接？',
								confirmText: '复制链接',
								cancelText: '取消',
								success: (modalRes) => {
									if (modalRes.confirm) {
										wx.setClipboardData({
											data: this.url,
											success: () => {
												wx.showToast({
													title: '链接已复制',
													icon: 'none'
												})
											}
										})
									}
								}
							})
						} else {
							wx.showToast({
								title: '下载失败，请检查网络',
								icon: 'none'
							})
						}
					},
					onProgressUpdate: (res) => {
						const progress = res.progress
						this.progress = progress
						
						wx.hideModal()
						wx.showModal({
							title: '正在下载',
							content: `${progress}%`,
							showCancel: false,
							confirmText: '下载中...',
							confirmColor: '#999999'
						})
					}
				})
			},
			//#endif
			handleDownloadSuccess(filePath, isTemp = false) {
				wx.showModal({
					title: '下载完成',
					content: isTemp 
						? 'APK文件已下载（临时文件），是否打开？\n注意：临时文件可能会被清理，请及时安装。' 
						: 'APK文件已下载，是否打开？',
					success: (modalRes) => {
						if (modalRes.confirm) {
							wx.openDocument({
								filePath: filePath,
								success: () => {
									console.log('文件已打开')
								},
								fail: (docErr) => {
									console.error('无法打开文件:', docErr)
									
									// 提示用户手动下载
									wx.showModal({
										title: '无法直接安装',
										content: '由于微信限制，无法直接安装APK文件。是否复制下载链接，在浏览器中下载？',
										confirmText: '复制链接',
										cancelText: '取消',
										success: (res) => {
											if (res.confirm) {
												wx.setClipboardData({
													data: this.url,
													success: () => {
														wx.showToast({
															title: '链接已复制',
															icon: 'none'
														})
													}
												})
											}
										}
									})
								}
							})
						}
					}
				})
			}
		}
	}
</script>

<style>
	.bottm {
		position: absolute;
		bottom: 0%;
		width: 750rpx;
		height: 514rpx;
		z-index: 10;
	}

	.beijin {
		position: absolute;
		width: 750rpx;
		height: 100vh;
		z-index: 1;
	}

	.download-btn {
		position: absolute;
		width: 620rpx;
		height: 100rpx;
		z-index: 999;
		bottom: 10%;
		left: 25%;
		transform: translateX(-50%);
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn-text {
		color: white;
		font-size: 36rpx;
		font-weight: bold;
	}
</style>